package com.taichuan.selfcheck.mvp.presenter;

import com.taichuan.mvp.base.MvpBasePresenter;
import com.taichuan.selfcheck.mvp.viewinterface.LightControlInterface;
import com.taichuan.serialcommunication.SerialPortPublic;


public class LightControlPresenter extends MvpBasePresenter<LightControlInterface> {
        private static final String TAG = LightControlPresenter.class.getSimpleName();
        private static final int GET_LIGHT_MODULE_VALUE_TIME = 1 * 1000;
        private GetLightValueRunnable getLightValueRunnable;
        private Thread getLightValueThread;

    @Override
    public void attachView(LightControlInterface view) {
        super.attachView(view);
        //开始光感数值获取
        startOrCloseGetLightValue(true);
    }

    @Override
        public void detachView() {
        super.detachView();
        //停止光感数值获取
        startOrCloseGetLightValue(false);
    }

        /**
         * 定义一个方法用于获取当前的的光感模块数值
         */
        public void startOrCloseGetLightValue(boolean isStart){
        if (isStart){
            if (getLightValueRunnable == null){
                getLightValueRunnable = new GetLightValueRunnable();
            }
            if (getLightValueThread == null){
                getLightValueThread = new Thread(getLightValueRunnable);
            }
            //开始定时获取光感模块数值
            getLightValueRunnable.setStart(true);
            getLightValueThread.start();
        }else {
            if (getLightValueRunnable != null){
                getLightValueRunnable.setStart(false);
                getLightValueRunnable = null;
            }

            if (getLightValueThread != null){
                getLightValueThread.interrupt();
                getLightValueThread = null;
            }
        }
    }

        private class GetLightValueRunnable implements Runnable {
            private boolean isStart = false;

            public void setStart(boolean start) {
                isStart = start;
            }

            @Override
            public void run() {
                while (isStart) {
                    try {
                        //间隔时间通知单片机上报光感数值
                        SerialPortPublic.getLighrPower();
                        //睡眠
                        Thread.sleep(GET_LIGHT_MODULE_VALUE_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

}
